package com.ogawa.project6602.base


import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.bean.DeviceStateChangeBean
import com.ogawa.base.constants.Constants
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.mqtt.MqttSendMsgCallback
import com.ogawa.base.utils.SpUtil
import com.ogawa.project6602.bean.Device6602StateBean
import com.ogawa.project6602.bean.Massage6602Armchair
import com.ogawa.projectcommon.activity.BaseMqttActivity
import com.ogawa.projectcommon.constants.IntentKeyConstant.LIVE_EVENT_BUS_KEY_DEVICE_STATE_CHANGE
import com.ogawa.projectcommon.constants.IntentKeyConstant.LIVE_EVENT_BUS_KEY_MSG_CALL_BACK
import org.eclipse.paho.client.mqttv3.IMqttActionListener
import org.eclipse.paho.client.mqttv3.IMqttToken
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.json.JSONObject

abstract class Base6602MqttActivity : BaseMqttActivity() {
    override fun abstractOnConnectStateChange(isConnect: Boolean) {
        mHandler.removeCallbacksAndMessages(null)
        if (isConnect) {
            dismissLoadingDialog()
            val sn: String = SpUtil.get(SpUtil.SN, "") as String
            val instance = MqttManager.getInstance()
            instance.subscribe(
                arrayOf(
                    "cmd/up/$sn",
                    "cmd/back/$sn/${instance.clientId}"
                ), intArrayOf(2, 2), object : IMqttActionListener {
                    override fun onSuccess(asyncActionToken: IMqttToken) {
                        publish(Constants.RUNNING_STATUS_QUERY, "")
                    }

                    override fun onFailure(
                        asyncActionToken: IMqttToken,
                        exception: Throwable
                    ) {
                        LogUtils.e("onFailure: " + (exception?.message))
                        onConnectStateChange(false)
                    }
                })
        } else {
            Massage6602Armchair.getInstance().runningStatus = 0
            Massage6602Armchair.getInstance().deviceStatusBean = null
            onDeviceStateChange()
        }
    }

    override fun abstractonReceiveMqttMsg(topic: String, message: MqttMessage) {
        val msg = String(message.payload)
        LogUtils.e("$TAG 处理消息 ${topic} :   ${msg}")

//        Log.e("tag", "---$topic---$msg-")

        if (topic.contains("up")) { //设备状态的消息
            if (!msg.contains("fault") && !msg.contains("elecTime") && !msg.contains("heartbeat")) {
                val deviceStatusBean: Device6602StateBean = GsonUtils.fromJson(
                    msg,
                    Device6602StateBean::class.java
                )
                val runningStatus = deviceStatusBean.functions.runningStatus
                if (runningStatus != null) {
                    val state = runningStatus.modelValue.toInt()
                    Massage6602Armchair.getInstance().runningStatus = state
                    if (state == 0) {
                        Massage6602Armchair.getInstance().deviceStatusBean = null
                    }
                }
                val resetSucccessFlag = deviceStatusBean.functions.resetSucccessFlag
                if (resetSucccessFlag != null) { //复位标志即为关机信号
                    Massage6602Armchair.getInstance().runningStatus = 0
                    Massage6602Armchair.getInstance().reset = resetSucccessFlag.modelValue.toInt()
                    //                    DeviceOffBean deviceOffBean = mGson.fromJson(msg, DeviceOffBean.class);
                    Massage6602Armchair.getInstance().deviceStatusBean = null
                    //                    MassageArmchair.getInstance().setDeviceOffBean(deviceOffBean);
                }
                if (deviceStatusBean.functions.autoProgram != null) {
                    Massage6602Armchair.getInstance().deviceStatusBean = deviceStatusBean
                    Massage6602Armchair.getInstance().deviceOffBean = null
                }
            } else if (msg.contains("fault")) { //设备故障码
                val functions: String = JSONObject(msg).getString("functions")
                val fault = JSONObject(functions).getString("fault")
                val faultResult = JSONObject(fault).getString("modelValue")
                Massage6602Armchair.getInstance().fault = faultResult
            }
            LiveEventBus.get(
                LIVE_EVENT_BUS_KEY_DEVICE_STATE_CHANGE,
                DeviceStateChangeBean::class.java
            ).post(DeviceStateChangeBean())
        } else if (topic.contains("back")) { //发送消息的回复
            val cmdResult: String = JSONObject(msg).getString("cmdResult")
            var sendState = 0
            when (cmdResult) {
                "success" -> sendState = MqttSendMsgCallback.SUCCESS
                "fail" -> sendState = MqttSendMsgCallback.FAIL
                "timeout" -> sendState = MqttSendMsgCallback.TIMEOUT
                "offline" -> sendState = MqttSendMsgCallback.OFFLINE
            }
//            for (mMsgSendCallback in mMsgSendCallbacks) {
//                mMsgSendCallback.sendMsgCallback(sendState)
//            }
//            sendMsgCallback(sendState)
            LiveEventBus.get(LIVE_EVENT_BUS_KEY_MSG_CALL_BACK, Int::class.java).post(sendState)
        }
    }


}